package com.rrd.hive.udf;

import com.weicai.caesar.CaesarUtil;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;

import java.security.NoSuchAlgorithmException;


@Description(
        name = "caesar_blur",
        value = "_FUNC_(str) - get blur str",
        extended = "Example:\n> SELECT _FUNC_('13811360000');\n  138****0000\n> SELECT _FUNC_('6jxdXEKdEo/bHVdtUWshLZmfEBahoIMjHUUtRRjvrJM=');\n  138****0000"
)
public class CaesaBlurUDF extends UDF {

    public Text evaluate(String str) throws NoSuchAlgorithmException {
        Text text = new Text();
        if (str == null || str.equals("")) {
            return null;
        }
        if (CaesarUtil.isEncrypted(str)) {
            str = CaesarUtil.decode(str);
        }
        String result;
        int middle;
        if (str.length() > 1 && str.length() <= 5) {
            result = str.substring(0, 1) + "**";
        } else if (str.length() <= 10) {
            result = "**";
        } else if (str.length() == 11) {
            result = str.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        } else if (str.length() == 18) {
            result = str.replaceAll("(\\d{6})\\d{8}((\\d|\\w){4})", "$1********$2");
        } else {
            middle = str.length() - 8;
            result = str.replaceAll("(\\w{4})\\w{" + middle + "}(\\w{4})", "$1****$2");
        }
        text.set(result);

        return text;
    }


    public static void main(String[] args) throws Exception {
        CaesaBlurUDF udf = new CaesaBlurUDF();
        System.out.println(udf.evaluate("53242819930206032z").toString());

    }
}
